package com.dzwww.recommend.rule.common.api;

import org.apache.commons.lang3.StringUtils;

/**
 * <pre>
 * 接口请求返回的统一业务异常类，包括SOA服务接口的调用。 通过该异常类统一将出错的业务信息返回给消费端
 * 
 * @author Winner
 */
public class ApiException extends RuntimeException {
	private static final long serialVersionUID = 2685287081293576410L;
	private String code;
	private String message;
	private Object[] args;
	/** 区分运行期异常与业务异常 */
	private boolean runtime;

	/**
	 * 当带有参数时，文本将通过类 Slf4j 占位符形式进行格式化
	 * 
	 * @param code
	 * @param message
	 */
	public ApiException(String code, String message) {
		this.code = code;
		this.message = message;
	}

	/**
	 * 当带有参数时，文本将通过类 Slf4j 占位符形式进行格式化
	 * 
	 * @param message 异常信息
	 * @param args 消息占位符的替换参数
	 */
	public ApiException(ApiMessage message, Object... args) {
		this.code = message.getCode();
		this.message = message.formatMessage(args);
		this.args = args;
	}

	public ApiException(Throwable e) {
		super(e);
		this.code = e.getClass().getName();
		this.message = StringUtils.join(this.code, " - ", e.getMessage());
		this.runtime = true;
	}

	@Override
	public Throwable fillInStackTrace() {
		return this;
	}

	public String getCode() {
		return code;
	}

	@Override
	public String getMessage() {
		return message;
	}

	public Object[] getArgs() {
		return args;
	}

	public boolean isRuntime() {
		return runtime;
	}

	public void setRuntime(boolean runtime) {
		this.runtime = runtime;
	}

//	private void resolveMessage() {
//		if (StringUtils.isBlank(this.message) || this.args == null || this.args.length < 1) {
//			return;
//		}
//		this.message = StringPlaceholderFormatter.format(this.message, this.args);
//	}
}
